package com.atguigu.day08;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.e;

public class Flink02_TableAPI_Demo_Agg {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.获取数据
//        DataStreamSource<WaterSensor> waterSensorStream =
//                env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
//                        new WaterSensor("sensor_1", 2000L, 20),
//                        new WaterSensor("sensor_2", 3000L, 30),
//                        new WaterSensor("sensor_1", 4000L, 40),
//                        new WaterSensor("sensor_1", 5000L, 50),
//                        new WaterSensor("sensor_2", 6000L, 60));
        SingleOutputStreamOperator<WaterSensor> waterSensorStream = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                });

        //TODO 获取表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //TODO 将流转为动态表
        Table table = tableEnv.fromDataStream(waterSensorStream);

        //TODO 通过连续查询查询出数据并生成动态的结果表   按照Id进行groupBy，求VC的和
        Table resuleTable = table
                .groupBy($("id"))
                .select($("id"), $("vc").sum().as("vcSum"));


        //TODO 将结果表转为流 (撤回流)
//        DataStream<Row> result = tableEnv.toAppendStream(resuleTable, Row.class);
        DataStream<Tuple2<Boolean, Row>> result = tableEnv.toRetractStream(resuleTable, Row.class);
        result.print();

        env.execute();

    }
}
